//
//  RHNavigationController.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/5.
//

#import "RHNavigationController.h"
#import "RHBaseViewController.h"
#import "RHOverviewVC.h"
#import "NetworkAgent.h"

@interface RHNavigationController ()

@property (nonatomic, strong) UIButton *backButton;

@property (nonatomic, strong) UIImage *shadowImage;

@end

@implementation RHNavigationController

- (instancetype)initWithRootViewController:(UIViewController *)rootViewController
{
    if (self = [super initWithRootViewController:rootViewController]) {
        
       // self.shadowImage = self.navigationBar.shadowImage;
        [self.view setBackgroundColor:UIColor.whiteColor];
        [self.navigationBar setBackgroundImage:[self imageWithColor:[UIColor colorWithHexString:@"#ffffff"]] forBarMetrics:UIBarMetricsDefault];
        self.navigationBar.shadowImage = [self imageWithColor:[UIColor colorWithHexString:@"#ffffff"]];
        [self.navigationBar setTranslucent:NO];
        //self.navigationBar.shadowImage = [[UIImage alloc] init];
        //self.shadowImage = self.navigationBar.shadowImage;
       
        if (@available(iOS 13.0, *)) {
           
        } else {
            [self.navigationBar setTitleTextAttributes:@{
                                                             NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#333333"],
                                                             NSFontAttributeName:[UIFont boldSystemFontOfSize:18]
                                                             }];
        }
 
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 重新设置侧滑手势的代理
    __weak typeof(self) weakSelf = self;
    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]){
        self.interactivePopGestureRecognizer.delegate = (id)weakSelf;
    }
    
    if (@available(iOS 13.0, *)) {
        
        UINavigationBarAppearance *barAppearance = UINavigationBarAppearance.new;
        [barAppearance configureWithOpaqueBackground];
        [barAppearance setBackgroundImage:[self backgroundImageWithColor:[UIColor whiteColor]]];
        [barAppearance setShadowImage:[self imageWithColor:[UIColor colorWithHexString:@"#ffffff"]]];
        self.navigationBar.standardAppearance = barAppearance;
        self.navigationBar.scrollEdgeAppearance = barAppearance;
        self.navigationBar.shadowImage = [self imageWithColor:[UIColor colorWithHexString:@"#ffffff"]];
    }

}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if(self.viewControllers.count >= 1)
    {
        //self.backActionBlock = nil;
        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,45, 44)];
//        [backButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
//        [backButton setTitle:@"" forState:UIControlStateNormal];
//        [backButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
//        [backButton setContentEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
//        [backButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
//        [backButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
//        [backButton addTarget:self action:@selector(didClickBack:) forControlEvents:UIControlEventTouchUpInside];
//        UIBarButtonItem *leftBarBtn = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//        spaceItem.width = -5;
//        viewController.navigationItem.leftBarButtonItems = @[leftBarBtn,spaceItem];
        
        UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(didClickBack:)];
        closeItem.accessibilityLabel = @"back";
        viewController.navigationItem.leftBarButtonItem = closeItem;
        
        viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
        //当vc被push进入nav时隐藏底部bar
        viewController.hidesBottomBarWhenPushed = YES;
        self.backButton = backButton;
        //self.navigationBar.shadowImage = self.shadowImage;
    }
    
    //这句会立即调用被push的VC的viewDidLoad方法，必须放在最后面，否则上面的代码会对viewDidLoad中代码造成覆盖，导致viewDidLoad设置无效。
    [super pushViewController:viewController animated:animated];//animated换为NO，所有VC没有动画
}

- (UIViewController *)childViewControllerForStatusBarStyle {
    return self.topViewController;
}

#pragma mark -- 自定义方法

//设置导航栏透明
-(void)setBackgoundClear:(BOOL)status titleColor:(UIColor*)color;
{
    
//    [self.navigationBar setBackgroundColor:status?[UIColor redColor]:UIColor.whiteColor];
    if(color){
        [self.navigationBar setTitleTextAttributes:@{
                                                         NSForegroundColorAttributeName:color,
                                                         NSFontAttributeName:[UIFont boldSystemFontOfSize:18]
                                                         }];
    }
    [self.navigationBar setBackgroundImage:[self imageWithColor:status?[UIColor clearColor]:[UIColor colorWithHexString:@"#ffffff"]] forBarMetrics:UIBarMetricsDefault];
    self.navigationBar.shadowImage = [self imageWithColor:status?[UIColor clearColor]:[UIColor colorWithHexString:@"#ffffff"]];
    self.navigationBar.backgroundColor = status?[UIColor clearColor]:[UIColor whiteColor];
    self.navigationBar.translucent = status;
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *barAppearance = UINavigationBarAppearance.new;
        if(status){
            //背景色透明
            [barAppearance configureWithTransparentBackground];
  
        }else{
            //背景色不透明
            [barAppearance configureWithOpaqueBackground];
        }
        if(color){
            barAppearance.titleTextAttributes = @{NSForegroundColorAttributeName:color, NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
        }
        [barAppearance setBackgroundImage:[self imageWithColor:status?[UIColor clearColor]:[UIColor colorWithHexString:@"#ffffff"]]];
        
        [barAppearance setShadowImage:[self imageWithColor:status?[UIColor clearColor]:[UIColor colorWithHexString:@"#ffffff"]]];
        self.navigationBar.standardAppearance = barAppearance;
        self.navigationBar.scrollEdgeAppearance = barAppearance;
        self.navigationBar.shadowImage = [self imageWithColor:status?[UIColor clearColor]:[UIColor colorWithHexString:@"#ffffff"]];
    }
}

- (void)didClickBack:(UIButton *)button
{
    //取消没有响应的请求
    [[NetworkAgent sharedAgent] cancelAllRequests];
    if (self.backActionBlock) {
        self.backActionBlock();
        self.backActionBlock = nil;
    }else{
        NSLog(@"popView");
        [self popViewControllerAnimated:YES];
    }
}

- (void)hideBackButton
{
    self.backButton.hidden = YES;
}

- (void)showBackButton
{
    self.backButton.hidden = NO;
}

- (void)setBackTitle:(NSString *)title
{
    [self.backButton setTitle:title forState:UIControlStateNormal];
}

#pragma mark -- 懒加载
- (UIButton *)backButton
{
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    }
    return _backButton;
}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *imgae = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imgae;
}
- (UIImage *)backgroundImageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, kUI_WINDOW_W, kNavHeight);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *imgae = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imgae;
}
// 开始接收到手势的代理方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    // 判断是否是侧滑相关的手势
    if (gestureRecognizer == self.interactivePopGestureRecognizer) {
        // 如果当前展示的控制器是根控制器就不让其响应
        RHBaseViewController *controller = (RHBaseViewController *)self.visibleViewController;
        if (self.viewControllers.count < 2 || self.visibleViewController == [self.viewControllers objectAtIndex:0]||controller.isUnPopGes) {
            return NO;
        }
    }
    return YES;
}

// 接收到多个手势的代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // 判断是否是侧滑相关手势
    if (gestureRecognizer == self.interactivePopGestureRecognizer && [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]){
        UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)gestureRecognizer;
        CGPoint point = [pan translationInView:self.view];
        // 如果是侧滑相关的手势，并且手势的方向是侧滑的方向就让多个手势共存
        if (point.x > 0) {
            return YES;
        }
    }
    return NO;
}

-(void)setBackgoundColor:(UIColor *)color
{
    [self.navigationBar setBackgroundImage:[self imageWithColor:color] forBarMetrics:UIBarMetricsDefault];
    self.navigationBar.shadowImage = [self imageWithColor:color];
    self.navigationBar.backgroundColor = color;
    self.navigationBar.translucent = NO;
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *barAppearance = UINavigationBarAppearance.new;
        //背景色不透明
        [barAppearance configureWithOpaqueBackground];
        [barAppearance setBackgroundImage:[self imageWithColor:color]];
        [barAppearance setShadowImage:[self imageWithColor:color]];
        self.navigationBar.standardAppearance = barAppearance;
        self.navigationBar.scrollEdgeAppearance = barAppearance;
        self.navigationBar.shadowImage = [self imageWithColor:color];
    }
}


@end
